<template>
    <view class="container">
      <!-- 页面头部 -->
      <view class="header">
        <view class="type-info">
          <view class="type-title">{{ currentTypeName }}</view>
          <view class="type-desc">{{ currentTypeDesc }}</view>
        </view>
        <view class="progress-info">
          <view class="progress-text">{{ currentQuestionIndex + 1 }} / {{ totalQuestions }}</view>
        </view>
      </view>
  
      <!-- 题目卡片 -->
      <view class="question-container" v-if="currentQuestion">
        <question-card 
          :question="currentQuestion"
          :question-index="currentQuestionIndex"
          :show-answer="showAnswer"
          @answer-selected="onAnswerSelected"
          @toggle-answer="toggleAnswer"
        />
      </view>
  
      <!-- 加载状态 -->
      <view class="loading-container" v-else-if="loading">
        <u-loading-icon mode="circle"></u-loading-icon>
        <text class="loading-text">正在加载题目...</text>
      </view>
  
      <!-- 无题目状态 -->
      <view class="empty-container" v-else>
        <view class="empty-icon">📝</view>
        <text class="empty-text">暂无题目</text>
        <button class="retry-btn" @click="loadQuestions">重新加载</button>
      </view>
  
      <!-- 底部操作栏 -->
      <view class="bottom-bar" v-if="currentQuestion">
        <view class="action-buttons">
          <!-- 收藏按钮 -->
          <view class="action-btn" @click="toggleFavorite">
            <u-icon 
              :name="currentQuestion.isFavorite ? 'heart-fill' : 'heart'" 
              :color="currentQuestion.isFavorite ? '#ff4757' : '#999'" 
              size="24"
            ></u-icon>
            <text class="btn-text">{{ currentQuestion.isFavorite ? '已收藏' : '收藏' }}</text>
          </view>
  
          <!-- 显示答案按钮 -->
          <view class="action-btn" @click="toggleAnswer" v-if="!showAnswer">
            <u-icon name="eye" color="#007AFF" size="24"></u-icon>
            <text class="btn-text">看答案</text>
          </view>
  
          <!-- 下一题按钮 -->
          <view class="action-btn primary" @click="nextQuestion" v-if="showAnswer">
            <u-icon name="arrow-right" color="#ffffff" size="24"></u-icon>
            <text class="btn-text">下一题</text>
          </view>
        </view>
      </view>
  
      <!-- 完成提示弹窗 -->
      <u-popup :show="showCompletePopup" mode="center" :round="20" :closeable="true" :close-on-click-overlay="false">
        <view class="complete-popup">
          <view class="complete-icon">🎉</view>
          <view class="complete-title">练习完成！</view>
          <view class="complete-stats">
            <view class="stat-item">
              <text class="stat-number">{{ correctCount }}</text>
              <text class="stat-label">正确</text>
            </view>
            <view class="stat-item">
              <text class="stat-number">{{ errorCount }}</text>
              <text class="stat-label">错误</text>
            </view>
            <view class="stat-item">
              <text class="stat-number">{{ accuracy }}%</text>
              <text class="stat-label">正确率</text>
            </view>
          </view>
          <view class="complete-actions">
            <button class="action-button secondary" @click="restartPractice">重新练习</button>
            <button class="action-button primary" @click="goBack">返回</button>
          </view>
        </view>
      </u-popup>
    </view>
  </template>
  
  <script>
  import questionCard from '@/components/question-card/question-card.vue'
  
  export default {
    components: {
      questionCard
    },
    data() {
      return {
        bankId: '',
        questionType: 1, // 1单选 2多选 3判断
        questions: [], // 题目列表
        currentQuestionIndex: 0, // 当前题目索引
        currentQuestion: null, // 当前题目
        showAnswer: false, // 是否显示答案
        loading: true,
        totalQuestions: 0,
        correctCount: 0, // 正确题数
        errorCount: 0, // 错误题数
        showCompletePopup: false, // 显示完成弹窗
        
        // 题型信息
        typeInfo: {
          1: { name: '单选题', desc: '每题只有一个正确答案' },
          2: { name: '多选题', desc: '每题有多个正确答案' },
          3: { name: '判断题', desc: '判断对错' }
        }
      }
    },
    computed: {
      currentTypeName() {
        return this.typeInfo[this.questionType]?.name || '题目练习'
      },
      currentTypeDesc() {
        return this.typeInfo[this.questionType]?.desc || ''
      },
      accuracy() {
        const total = this.correctCount + this.errorCount
        return total > 0 ? Math.round((this.correctCount / total) * 100) : 0
      }
    },
    onLoad(options) {
      // 获取传入的参数
      this.bankId = options.bankId || ''
      this.questionType = parseInt(options.questionType) || 1
      
      if (!this.bankId) {
        uni.showToast({
          title: '题库信息异常',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
        return
      }
      
      // 加载题目
      this.loadQuestions()
    },
    methods: {
      // 加载题目
      loadQuestions() {
        this.loading = true
        this.questions = []
        this.currentQuestionIndex = 0
        this.currentQuestion = null
        this.showAnswer = false
        this.correctCount = 0
        this.errorCount = 0
        
        // 直接加载静态题目数据，不调用后端
        this.mockLoadQuestions()
      },
      
      // 加载静态题目数据
      mockLoadQuestions() {
        let mockQuestions = []
        
        // 根据题型生成不同的题目数据
        if (this.questionType === 1) {
          // 单选题数据
          mockQuestions = [
            {
              questionId: 1,
              questionTitle: '以下哪个是JavaScript的基本数据类型？',
              questionType: 1,
              options: [
                'A：Object',
                'B：String', 
                'C：Array',
                'D：Function'
              ],
              correctAnswer: 'B',
              explanation: 'JavaScript的基本数据类型包括：String、Number、Boolean、Undefined、Null、Symbol。Object、Array、Function都是引用类型。',
              isFavorite: false
            },
            {
              questionId: 2,
              questionTitle: 'CSS中哪个属性用于设置元素的背景颜色？',
              questionType: 1,
              options: [
                'A：color',
                'B：background-color',
                'C：bgcolor',
                'D：background'
              ],
              correctAnswer: 'B',
              explanation: 'background-color是CSS中专门用于设置元素背景颜色的属性。color属性用于设置文字颜色。',
              isFavorite: false
            },
            {
              questionId: 3,
              questionTitle: '在Vue.js中，以下哪个指令用于条件渲染？',
              questionType: 1,
              options: [
                'A：v-for',
                'B：v-if',
                'C：v-show',
                'D：v-bind'
              ],
              correctAnswer: 'B',
              explanation: 'v-if指令用于条件渲染，当条件为true时渲染元素，为false时不渲染。v-show是控制显示隐藏，v-for是循环渲染。',
              isFavorite: false
            },
            {
              questionId: 4,
              questionTitle: 'HTTP状态码200表示什么？',
              questionType: 1,
              options: [
                'A：请求失败',
                'B：请求成功',
                'C：服务器错误',
                'D：未找到资源'
              ],
              correctAnswer: 'B',
              explanation: 'HTTP状态码200表示请求成功，这是最常见的成功响应状态码。',
              isFavorite: false
            },
            {
              questionId: 5,
              questionTitle: '以下哪个不是HTML5的新特性？',
              questionType: 1,
              options: [
                'A：Canvas',
                'B：LocalStorage',
                'C：Flash',
                'D：WebSocket'
              ],
              correctAnswer: 'C',
              explanation: 'Flash不是HTML5的新特性，它是Adobe公司的技术。Canvas、LocalStorage、WebSocket都是HTML5引入的新特性。',
              isFavorite: false
            }
          ]
        } else if (this.questionType === 2) {
          // 多选题数据
          mockQuestions = [
            {
              questionId: 1,
              questionTitle: '以下哪些是前端开发中常用的框架？',
              questionType: 2,
              options: [
                'A：React',
                'B：Vue.js',
                'C：Angular',
                'D：jQuery'
              ],
              correctAnswer: 'ABCD',
              explanation: 'React、Vue.js、Angular都是现代前端开发的主流框架，jQuery虽然较老但仍然是常用的JavaScript库。',
              isFavorite: false
            },
            {
              questionId: 2,
              questionTitle: '以下哪些是CSS3的新特性？',
              questionType: 2,
              options: [
                'A：Flexbox布局',
                'B：Grid布局',
                'C：动画(Animation)',
                'D：渐变(Gradient)'
              ],
              correctAnswer: 'ABCD',
              explanation: 'Flexbox、Grid、Animation、Gradient都是CSS3引入的重要新特性，大大增强了CSS的布局和视觉效果能力。',
              isFavorite: false
            },
            {
              questionId: 3,
              questionTitle: '以下哪些是JavaScript的异步处理方式？',
              questionType: 2,
              options: [
                'A：Promise',
                'B：async/await',
                'C：回调函数',
                'D：Generator'
              ],
              correctAnswer: 'ABCD',
              explanation: 'Promise、async/await、回调函数、Generator都是JavaScript中处理异步操作的方式，各有其适用场景。',
              isFavorite: false
            },
            {
              questionId: 4,
              questionTitle: '以下哪些是HTTP请求方法？',
              questionType: 2,
              options: [
                'A：GET',
                'B：POST',
                'C：PUT',
                'D：DELETE'
              ],
              correctAnswer: 'ABCD',
              explanation: 'GET、POST、PUT、DELETE都是标准的HTTP请求方法，分别用于获取、创建、更新、删除资源。',
              isFavorite: false
            },
            {
              questionId: 5,
              questionTitle: '以下哪些是数据库类型？',
              questionType: 2,
              options: [
                'A：MySQL',
                'B：MongoDB',
                'C：Redis',
                'D：PostgreSQL'
              ],
              correctAnswer: 'ABCD',
              explanation: 'MySQL、MongoDB、Redis、PostgreSQL都是常见的数据库，其中MySQL和PostgreSQL是关系型数据库，MongoDB是文档型数据库，Redis是内存数据库。',
              isFavorite: false
            }
          ]
        } else if (this.questionType === 3) {
          // 判断题数据
          mockQuestions = [
            {
              questionId: 1,
              questionTitle: 'JavaScript是一种强类型语言。',
              questionType: 3,
              options: ['正确', '错误'],
              correctAnswer: '错误',
              explanation: 'JavaScript是一种弱类型（动态类型）语言，变量可以在运行时改变类型，不需要显式声明类型。',
              isFavorite: false
            },
            {
              questionId: 2,
              questionTitle: 'CSS中的margin属性可以设置负值。',
              questionType: 3,
              options: ['正确', '错误'],
              correctAnswer: '正确',
              explanation: 'CSS中的margin属性可以设置负值，负的margin值可以让元素向相反方向移动，常用于布局调整。',
              isFavorite: false
            },
            {
              questionId: 3,
              questionTitle: 'Vue.js是Facebook开发的框架。',
              questionType: 3,
              options: ['正确', '错误'],
              correctAnswer: '错误',
              explanation: 'Vue.js是由尤雨溪（Evan You）开发的，不是Facebook开发的。React才是Facebook开发的框架。',
              isFavorite: false
            },
            {
              questionId: 4,
              questionTitle: 'HTML5支持离线存储功能。',
              questionType: 3,
              options: ['正确', '错误'],
              correctAnswer: '正确',
              explanation: 'HTML5提供了localStorage和sessionStorage等离线存储功能，还支持Application Cache和IndexedDB等更强大的存储方案。',
              isFavorite: false
            },
            {
              questionId: 5,
              questionTitle: '所有的HTML标签都必须有闭合标签。',
              questionType: 3,
              options: ['正确', '错误'],
              correctAnswer: '错误',
              explanation: '不是所有HTML标签都需要闭合标签，如img、br、hr、input等自闭合标签就不需要闭合标签。',
              isFavorite: false
            },
            {
              questionId: 6,
              questionTitle: 'CSS选择器的优先级：内联样式 > ID选择器 > 类选择器 > 标签选择器。',
              questionType: 3,
              options: ['正确', '错误'],
              correctAnswer: '正确',
              explanation: 'CSS选择器优先级从高到低为：内联样式(1000) > ID选择器(100) > 类选择器(10) > 标签选择器(1)。',
              isFavorite: false
            }
          ]
        }
        
        this.questions = mockQuestions
        this.totalQuestions = mockQuestions.length
        this.currentQuestion = mockQuestions[0]
        this.loading = false
      },
      
      // 答案选择事件
      onAnswerSelected(answer) {
        if (this.showAnswer) return
        
        // 判断答案是否正确
        const isCorrect = answer === this.currentQuestion.correctAnswer
        
        if (isCorrect) {
          this.correctCount++
        } else {
          this.errorCount++
        }
        
        // 显示答案
        this.showAnswer = true
        
        // 显示结果提示
        uni.showToast({
          title: isCorrect ? '回答正确！' : '回答错误',
          icon: isCorrect ? 'success' : 'none',
          duration: 1500
        })
      },
      
      // 切换显示答案
      toggleAnswer() {
        this.showAnswer = !this.showAnswer
      },
      
      // 下一题
      nextQuestion() {
        if (this.currentQuestionIndex < this.questions.length - 1) {
          this.currentQuestionIndex++
          this.currentQuestion = this.questions[this.currentQuestionIndex]
          this.showAnswer = false
        } else {
          // 练习完成
          this.showCompletePopup = true
        }
      },
      
      // 切换收藏状态
      toggleFavorite() {
        this.currentQuestion.isFavorite = !this.currentQuestion.isFavorite
        
        // 这里应该调用API更新收藏状态
        // updateFavorite(this.currentQuestion.questionId, this.currentQuestion.isFavorite)
        
        uni.showToast({
          title: this.currentQuestion.isFavorite ? '已收藏' : '已取消收藏',
          icon: 'none',
          duration: 1000
        })
      },
      
      // 重新练习
      restartPractice() {
        this.showCompletePopup = false
        this.loadQuestions()
      },
      
      // 返回
      goBack() {
        this.showCompletePopup = false
        uni.navigateBack()
      }
    }
  }
  </script>
  
  <style scoped>
  page {
    background: linear-gradient(180deg, #f7f7fc 0%, #f2f6ff 100%);
    min-height: 100vh;
  }
  
  .container {
    min-height: 100vh;
    padding-bottom: 120rpx;
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background: #ffffff;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  }
  
  .type-info {
    flex: 1;
  }
  
  .type-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .type-desc {
    font-size: 24rpx;
    color: #666;
  }
  
  .progress-info {
    text-align: right;
  }
  
  .progress-text {
    font-size: 28rpx;
    color: #007AFF;
    font-weight: bold;
  }
  
  .question-container {
    padding: 0 30rpx;
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 200rpx 0;
  }
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
    margin-top: 30rpx;
  }
  
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 200rpx 0;
  }
  
  .empty-icon {
    font-size: 120rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
  
  .retry-btn {
    background: #007AFF;
    color: #ffffff;
    border: none;
    border-radius: 50rpx;
    padding: 20rpx 40rpx;
    font-size: 28rpx;
  }
  
  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #ffffff;
    padding: 20rpx 30rpx;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
    z-index: 100;
  }
  
  .action-buttons {
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  
  .action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx;
    border-radius: 15rpx;
    transition: all 0.3s ease;
  }
  
  .action-btn:active {
    background: #f0f0f0;
  }
  
  .action-btn.primary {
    background: #007AFF;
    color: #ffffff;
  }
  
  .action-btn.primary:active {
    background: #0056cc;
  }
  
  .btn-text {
    font-size: 22rpx;
    margin-top: 8rpx;
    color: inherit;
  }
  
  .action-btn.primary .btn-text {
    color: #ffffff;
  }
  
  .complete-popup {
    padding: 60rpx 40rpx;
    text-align: center;
    min-width: 500rpx;
  }
  
  .complete-icon {
    font-size: 120rpx;
    margin-bottom: 30rpx;
  }
  
  .complete-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 40rpx;
  }
  
  .complete-stats {
    display: flex;
    justify-content: space-around;
    margin-bottom: 50rpx;
  }
  
  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .stat-number {
    font-size: 48rpx;
    font-weight: bold;
    color: #007AFF;
    margin-bottom: 10rpx;
  }
  
  .stat-label {
    font-size: 24rpx;
    color: #666;
  }
  
  .complete-actions {
    display: flex;
    gap: 20rpx;
  }
  
  .action-button {
    flex: 1;
    padding: 25rpx;
    border-radius: 50rpx;
    font-size: 28rpx;
    border: none;
    transition: all 0.3s ease;
  }
  
  .action-button.secondary {
    background: #f0f0f0;
    color: #666;
  }
  
  .action-button.primary {
    background: #007AFF;
    color: #ffffff;
  }
  
  .action-button:active {
    opacity: 0.8;
  }
  </style>
  